﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using CprExam.Model;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using GLCommon;

namespace CprExam.ViewModel
{
    public class VmBase : ViewModelBase
    {
        protected readonly string LoginUrl = "/cq/login";
        protected readonly string SubmitUrl = "/cq/submit";

        protected void Send<T>(T message, MessageToken token)
        {
            Messenger.Default.Send<T>(message, token);
        }

        protected void Send(MessageToken token)
        {
            Messenger.Default.Send<object>(null, token);
        }

        protected void Register<T>(object recipient, MessageToken token, Action<T> action)
        {
            Messenger.Default.Register<T>(recipient, token, action);
        }

        protected void Register(object recipient, MessageToken token, Action<object> action)
        {
            Messenger.Default.Register<object>(recipient, token, action);
        }

        protected string GetSerial()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                return (from ManagementObject mo in searcher.Get() select mo["SerialNumber"].ToString().Trim()).FirstOrDefault();
            }
            catch
            {
                return System.Environment.MachineName;
            }
        }

        protected void GetMessage(Exception ex, ref string msg)
        {
            LogTool.WriteErrorLog(ex.Message, ex);
            if (ex.InnerException != null)
            {
                GetMessage(ex.InnerException, ref msg);
            }
            else
            {
                msg = ex.Message;
            }
        }
    }
}
